<template>
	<view class="app-container">
		<!-- 信息栏 -->
		<view class="info">
			<image :src="isLogin ? (userData.avatarUrl ? userData.avatarUrl : defaultAvatar) : defaultAvatar"
				class="app-avatar avatar" @click="toUpdateMyProfile"></image>
			<view class="nickname">{{ isLogin ? (userData.nickname ? userData.nickname : '捉友用户') : '未登录' }}</view>
			<view class="signature">{{ isLogin ? (userData.signature ? userData.signature : defaultSignature) :
				'这个用户还没有登录哦~' }}</view>
		</view>

		<!-- 气泡背景 -->
		<view class="bubble-list">
			<view v-for="item in 10" class="bubble" :key="item"></view>
		</view>

		<!-- 三个按钮 -->
		<view class="button-list">
			<u-button :color="themeColor" icon="heart-fill" iconColor="#fff" @click="toCollection">收藏</u-button>
			<u-button :color="themeColor" icon="bookmark-fill" iconColor="#fff">关注</u-button>
			<u-button :color="themeColor" icon="setting-fill" iconColor="#fff" @click="toUpdateMyProfile">设置</u-button>
		</view>

		<!-- 底部详情 -->
		<view class="footer-content">
			<!-- 标签页 -->
			<u-tabs :list="tablist" :lineColor="themeColor" :scrollable="false"
				:activeStyle="{ color: '#303133', fontWeight: 'bold', transform: 'scale(1.05)' }"
				@click="handleTabClick"></u-tabs>

			<!-- 我的桌游 -->
			<view v-if="currentTab == 0" class="my-game-list">
				<view class="my-game-item" v-for="item in gameList" :key="item.id" @click="toBoardgame(item.id)">
					<view class="game-image">
						<image :src="item.picture" mode="widthFix"></image>
					</view>
					<view class="my-game-info">
						<view class="my-game-name">{{ item.name }}</view>
					</view>
				</view>
				<view class="add-game-button" @click="toAddBoardgame">
					<view style="font-size: 64rpx">+</view>
					<view>添加桌游</view>
				</view>
			</view>

			<view v-if="currentTab == 1" class="my-post-list">
				<!-- 帖子内容 -->
				<view class="post app-box" v-for="item in postList" :key="item.id" @click="toPostPage(item.id)">
					<view class="author">
						<image :src="item.userVO.avatarUrl" class="app-avatar"></image>
						<view class="nickname">{{ item.userVO.nickname }}</view>
						<u-tag :text="'Lv.' + item.userVO.level" size="mini" :borderColor="themeColor"
							:bgColor="themeColor" color="#fff"></u-tag>
						<view class="more" @click.stop="handleOpenOperationPopup(item)"><u-icon name="more-dot-fill"
								size="14" color="#666"></u-icon></view>
					</view>
					<view class="detail">
						<view class="app-title">{{ item.title }}</view>
						<view class="app-content content">{{ item.content }}</view>
						<image v-if="item.images && item.images.length > 0" :src="item.images[0].url" mode="aspectFill">
						</image>
						<view class="detail-info">
							<view style="margin-right: auto">{{ item.time }} · {{ item.area }}</view>
							<view class="icon"><u-icon name="thumb-up-fill" :label="item.likes"
									:color="item.liked ? themeColor : '#999'"></u-icon></view>
							<view class="icon"><u-icon name="star-fill" :label="item.collect"
									:color="item.collected ? themeColor : '#999'"></u-icon></view>
							<view class="icon"><u-icon name="chat-fill" :label="item.comments" color="#999"></u-icon>
							</view>
						</view>
					</view>
				</view>
				<Popup :show="showOperationPopup" @close="handleCloseOperationPopup">
					<view class="operation-bar">
						<view class="cell cell-title">{{ operationItem.title }}</view>
						<view class="cell" @click="handleEditPost"> 编辑 </view>
						<view class="cell cell-delete" @click="handleDeletePost"> 删除 </view>
						<view class="cell" @click="showOperationPopup = false"> 取消 </view>
					</view>
				</Popup>
			</view>

			<view v-if="currentTab == 2" class="my-activity-list">
				<view class="activity-wrapper">
					<view v-if="activityList.length == 0" class="no-activity">
						<u-empty mode="data" text="暂无活动！"> </u-empty>
					</view>
					<view v-else class="activity-list">
						<view v-for="item in activityList" :key="item.id" class="activity-item"
							@click="toActivityDetail(item)">
							<view class="activity-title">
								<view class="title">{{ item.title }}</view>
								<view class="tag"
									:class="item.status == '进行中' ? 'ongoing' : item.status == '已结束' ? 'ended' : 'pending'">
									{{
										item.status
									}}</view>
							</view>
							<view class="activity-info">
								<view class="activity-info-item">
									<u-icon name="clock" color="#4B5563" size="16"></u-icon>
									{{ item.date }} <view class="highline">{{ item.time }}</view>
								</view>
								<view class="activity-info-item">
									<u-icon name="map" color="#4B5563" size="16"></u-icon>
									{{ item.locationName }}
								</view>
								<view class="activity-info-item">
									<view class="players">
										<image v-for="player in item.participantVoList" :key="player.id"
											:src="player.user.avatarUrl" />
										<image :src="item.userVo.avatarUrl" />
									</view>
									<u-icon name="account" color="#4B5563" size="16" style="margin-right: 0px"></u-icon>
									<view>{{ item.participantVoList ? item.participantVoList.length + 1 : 1 }}/{{
										item.peopNum }}人</view>
									<u-button>查看</u-button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- Tabbar -->
		<Tabbar :active="4"></Tabbar>
	</view>
</template>

<script>
import request from '@/api/http.js';
import { timeCalc } from '@/api/utils.js';
import Popup from '@/components/Popup/Popup.vue'; // 弹出层

export default {
	components: {
		Popup // 注册弹出层组件
	},
	data() {
		return {
			userData: {
				nickname: '加载中...',
				signature: '加载中...'
			},
			tablist: [
				{
					name: '我的桌游'
				},
				{
					name: '我的帖子'
				},
				{
					name: '我的活动'
				}
			],
			gameList: [],
			postList: [],
			activityList: [],
			isLogin: false,
			currentTab: 0,
			showOperationPopup: false, // 操作弹出层
			operationItem: null, // 操作的帖子、活动、桌游
		};
	},
	onShow() {
		if (uni.getStorageSync('token')) {
			this.isLogin = true;
			this.getUserData();
			this.getGameList();
			this.getPostList();
			this.getActivityList();
		} else {
			this.isLogin = false;
		}
	},
	methods: {
		// 异步获取用户数据
		async getUserData() {
			// 发送请求，获取用户数据
			const res = await request(`/user/getUserData`);
			// 将获取到的数据赋值给userData
			this.userData = res.data;
		},
		// 跳转到更新个人资料页面
		toUpdateMyProfile() {
			if (uni.getStorageSync('token')) {
				// 使用uni.navigateTo方法跳转到更新个人资料页面
				uni.navigateTo({
					url: './UpdateMyProfile/UpdateMyProfile'
				});
			} else {
				uni.navigateTo({
					url: '../Login/LoginPage'
				});
			}
		},
		// 异步获取桌游列表
		async getGameList() {
			// 发送请求，获取桌游列表
			const res = await request(`/game/page`);
			// 将获取到的桌游列表赋值给gameList
			let gameList = res.data.list;
			this.gameList = gameList;
		},
		async getPostList() {
			let userId = uni.getStorageSync('userId');
			let res = await request('/forum/page', { userId });
			let postList = res.data.list;

			postList.forEach((item) => {
				item.time = timeCalc(item.createTime);
			});

			// 将获取到的帖子列表赋值给postList
			this.postList = postList;
		},
		async getActivityList() {
			const res = await request('/activities/queryUserActivities');
			this.activityList = res.data
				.sort((prev, next) => {
					return new Date(next.startTime) - new Date(prev.startTime);
				})
				.map((item) => {
					let status = '已结束';
					if (new Date(item.startTime) > new Date()) {
						status = '未开始';
					} else if (new Date(item.endTime) > new Date()) {
						status = '进行中';
					}
					return {
						...item,
						date: this.actTimeCalc(item.startTime),
						time: item.startTime.split(' ')[1] + '-' + item.endTime.split(' ')[1],
						status: status
					};
				});
		},
		actTimeCalc(time) {
			// 今天、明天、后天、月份-日期
			const today = new Date();
			const targetDate = new Date(time);
			const diff = targetDate - today;
			const diffDays = Math.round(diff / (1000 * 60 * 60 * 24));
			if (diffDays == 0) {
				return `今天`;
			} else if (diffDays == 1) {
				return '明天';
			} else if (diffDays == 2) {
				return '后天';
			} else {
				return `${targetDate.getMonth() + 1 < 10 ? '0' + (targetDate.getMonth() + 1) : targetDate.getMonth() + 1}-${targetDate.getDate()}`;
			}
		},
		toActivityDetail(item) {
			uni.navigateTo({
				url: `/pages/Activity/ActivityDetail/ActivityDetail?id=${item.id}`
			});
		},
		toPostPage(id) {
			uni.navigateTo({
				url: `/pages/Forum/PostPage?id=${id}`
			});
		},
		// 跳转到桌游页面
		toBoardgame(id) {
			uni.navigateTo({
				url: `../Boardgame/Boardgame/Boardgame?id=${id}`
			});
		},
		toAddBoardgame() {
			uni.navigateTo({
				url: `../Boardgame/AddBoardgame/AddBoardgame?mode=mePage`
			});
		},
		toCollection() {
			uni.navigateTo({
				url: `./Collection/Collection`
			});
		},
		handleTabClick(e) {
			this.handleCloseOperationPopup(); // 先关闭操作弹出层
			const index = e.index;
			this.currentTab = index;
		},
		handleOpenOperationPopup(item) {
			this.showOperationPopup = true;
			this.operationItem = item;
		},
		handleCloseOperationPopup() {
			// 关闭操作弹出层
			this.showOperationPopup = false;
			this.operationItem = null;
		},
		// 编辑帖子
		handleEditPost() {
			uni.navigateTo({
				url: `../Forum/CreatePost/CreatePost`,
				success: (res) => {
					res.eventChannel.emit('editPost', this.operationItem); // 发送编辑事件
					this.handleCloseOperationPopup(); // 关闭操作弹出层
				},
			});
		},
		// 删除帖子
		handleDeletePost() {
			uni.showModal({
				title: '真的要删除该帖子？',
				content: '即将删除这个帖子：' + this.operationItem.title,
				confirmColor: '#dd524d',
				confirmText: '删除',
				success: (modal) => {
					if (modal.confirm) {
						// 发送请求，删除帖子
						const res = request(`/forum/deletePost?id=${this.operationItem.id}`, {}, 'DELETE');
						uni.showToast({
							title: '删除成功',
							icon: 'none'
						});
						// 删除后页面有一点延迟
						this.$nextTick(() => {
							this.getPostList(); // 重新获取帖子列表
						})
						this.handleCloseOperationPopup(); // 关闭操作弹出层
					}
				},
			})
		}
	}
};
</script>

<style lang="scss">
page {
	background-color: #fcfcfc;
}

.container {
	padding: $container-padding-height 0;
	padding-bottom: 0;
	position: relative;
}

.info {
	display: flex;
	flex-direction: column;
	align-items: center;

	.avatar {
		width: 200rpx;
		height: 200rpx;
		margin: 20rpx;
	}

	.nickname {
		font-size: $font-size-large;
		font-weight: bold;
	}

	.signature {
		font-size: $font-size-base;
		color: $theme-color;
		text-align: center;
		line-height: 2em;
		background-color: #fff;
		margin: 20rpx;
		padding: 0 2em;
		border-radius: 50rpx;
	}
}

.bubble-list {
	width: 750rpx;
	height: 900rpx;
	background: linear-gradient(to bottom right, $theme-color-light, $theme-color);
	position: absolute;
	top: 0;
	z-index: -10;

	.bubble {
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		background-color: rgba(255, 255, 255, 0.15);
		border-radius: 20rpx;
		animation: floatUp 15s infinite;
		z-index: -1;
		bottom: 0;
	}

	.bubble:nth-child(1) {
		left: 10%;
	}

	.bubble:nth-child(2) {
		left: 20%;
		width: 60rpx;
		height: 60rpx;
		animation-delay: 2s;
		animation-duration: 8s;
	}

	.bubble:nth-child(3) {
		left: 25%;
		animation-delay: 6s;
		animation-duration: 9s;
	}

	.bubble:nth-child(4) {
		left: 0%;
		width: 120rpx;
		height: 120rpx;
		animation-duration: 8s;
		background-color: rgba(255, 255, 255, 0.3);
	}

	.bubble:nth-child(5) {
		left: 70%;
		animation-delay: 7s;
	}

	.bubble:nth-child(6) {
		left: 80%;
		width: 80rpx;
		height: 80rpx;
		animation-delay: 3s;
		background-color: rgba(255, 255, 255, 0.2);
	}

	.bubble:nth-child(7) {
		left: 32%;
		width: 300rpx;
		height: 300rpx;
		animation-delay: 2s;
	}

	.bubble:nth-child(8) {
		left: 55%;
		width: 50rpx;
		height: 50rpx;
		animation-delay: 4s;
		animation-duration: 8s;
	}

	.bubble:nth-child(9) {
		left: 75%;
		width: 40rpx;
		height: 40rpx;
		animation-delay: 2s;
		animation-duration: 6s;
		background-color: rgba(255, 255, 255, 0.3);
	}

	.bubble:nth-child(10) {
		left: 85%;
		width: 160rpx;
		height: 160rpx;
		animation-delay: 5s;
	}

	@keyframes floatUp {
		0% {
			opacity: 0.5;
			transform: translateY(0rpx) rotate(45deg);
		}

		25% {
			opacity: 0.75;
			transform: translateY(-400rpx) rotate(90deg);
		}

		50% {
			opacity: 1;
			transform: translateY(-800rpx) rotate(135deg);
		}

		100% {
			opacity: 0;
			transform: translateY(-1200rpx) rotate(180deg);
		}
	}
}

.button-list {
	display: flex;
	margin: 20rpx;

	.u-button {
		margin: 0 10rpx;
	}
}

.footer-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 750rpx;
	min-height: 900rpx;
	border-top-left-radius: 25rpx;
	border-top-right-radius: 25rpx;
	background-color: #fbfbfb;
	margin-top: 20rpx;

	.u-tabs {
		margin: 0 50rpx;
	}

	.my-game-list {
		width: calc(100% - 80rpx);
		padding: 20rpx;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 40rpx 20rpx;

		.my-game-item {
			display: flex;
			flex-direction: column;
			background-color: #fff;
			border-radius: 25rpx;
			width: 100%;
			box-shadow: 0 3px 9px #eee;
			overflow: hidden;

			.game-image {
				height: 300rpx;
				min-height: 300rpx;
				max-height: 300rpx;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
					object-fit: contain;
				}
			}

			.my-game-info {
				display: flex;
				padding: 20rpx;

				.my-game-name {
					font-size: $font-size-base;
				}
			}
		}
	}

	.add-game-button {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 330rpx;
		gap: 20rpx;
		color: $theme-color;
		background-color: #fff;
		font-size: $font-size-base;
		border-radius: 25rpx;
		border: 2px dashed $theme-color;
		padding: 20rpx 0;
		z-index: 10;
		box-shadow: 0px 3px 9px #eee;
	}
}

.post {
	.author {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.nickname {
			margin-right: 20rpx;
		}

		.more {
			margin-left: auto;
			margin-right: 10rpx;
			font-size: 32rpx;
			background-color: #f5f5f5;
			border-radius: 100%;
			padding: 12rpx;
		}
	}

	.detail {
		.content {
			width: 100%;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 5;
			overflow: hidden;
		}

		image {
			border-radius: 30rpx;
			width: 100%;
		}

		&-info {
			display: flex;
			justify-content: flex-end;
			color: #999;
			margin-top: 10rpx;
			padding-top: 10rpx;
			border-top: 1px gainsboro solid;
			font-size: $font-size-small;

			.icon {
				margin-right: 20rpx;
			}
		}
	}
}

.activity-wrapper {
	width: $max-width;
	flex: 1;
	overflow-y: scroll;

	.activity-list {
		margin: 20rpx 0;
		padding: 0 20rpx;

		.activity-item {
			display: flex;
			flex-direction: column;
			margin-bottom: 20rpx;
			background-color: #fff;
			border-radius: 25rpx;
			padding: 40rpx;
			box-shadow: 0 3px 9px #eee;
			border: 1px solid #eee;
			color: #4b5563;

			.activity-title {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.title {
					font-size: 32rpx;
					font-weight: bold;
					margin-bottom: 20rpx;
				}

				.tag {
					padding: 4rpx 8rpx;
					background-color: $theme-color-bg;
					color: $theme-color;
					font-size: 24rpx;
					border-radius: 25rpx;
					padding: 10rpx 20rpx;
				}

				.ongoing {
					background-color: #f5fff0;
					color: #5ac725;
				}

				.ended {
					background-color: #eee;
					color: #666;
				}
			}

			.activity-info {
				display: flex;
				flex-direction: column;
				font-size: $font-size-base;
				gap: 10px;

				.activity-info-item {
					display: flex;
					align-items: center;
					gap: 10px;

					.players {
						display: flex;
						align-items: center;
						margin-right: 40rpx;
						width: 100rpx;

						image {
							width: 50rpx;
							height: 50rpx;
							border-radius: 100%;
							margin-right: -30rpx;
							border: 2px solid #fff;
						}
					}

					.highline {
						color: $theme-color-light;
					}

					.u-button {
						width: 100rpx;
						height: 60rpx;
						font-size: $font-size-small;
						margin-left: auto;
						margin-right: 0;
						background-color: $theme-color;
						color: #fff;
						border-radius: 8px;
					}
				}
			}
		}
	}
}

.operation-bar {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 100%;

	.cell {
		display: flex;
		justify-content: center;
		width: 100%;
		padding: 30rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		font-size: $font-size-base;
		border-bottom: 1px solid #eee;
		color: #666;


		&-title {
			font-weight: bold;
			color: #333;
			border-bottom: 10rpx solid #eee;
		}

		/* 删除 */
		&-delete {
			color: $uni-color-error;
		}

		/* 最后一个 */
		&:last-child {
			border-top: 10rpx solid #eee;
		}

		// &:nth-child:last-child {
		// 	border-top: 10rpx solid #eee;
		// }
	}
}

.no-activity {
	margin-top: 100rpx;
}
</style>
